package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.ResultData;
import com.itheima.youdianda.dto.ArticleDto;
import com.itheima.youdianda.entity.YddArticle;
import com.itheima.youdianda.entity.YddCate;
import com.itheima.youdianda.entity.YddUser;
import com.itheima.youdianda.entity.YddUserData;
import com.itheima.youdianda.service.YddArticleService;
import com.itheima.youdianda.service.YddCateService;
import com.itheima.youdianda.service.YddUserDataService;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    public YddArticleService yddArticleService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddCateService yddCateService;

    @Autowired
    private YddUserDataService yddUserDataService;

    @GetMapping("/delArticle")
    public ResultData delArticle(String id, String token) {
        boolean b = yddArticleService.removeById(id);
        return ResultData.ok("", b);
    }


    @PostMapping("/addArticle")
    public ResultData addArticle(@RequestBody YddArticle yddArticle) {
        yddArticleService.save(yddArticle);
        return ResultData.ok(" ", " ");
    }


    @PostMapping("update")
    public ResultData update(@RequestBody YddUser yddUser) {
        yddUserService.updateById(yddUser);
        return ResultData.ok("修改成功", "");
    }


    @PostMapping("editArticle")
    public ResultData editArticle(@RequestBody YddArticle yddArticle) {
        yddArticleService.updateById(yddArticle);
        return ResultData.ok("修改成功", "");
    }


    @GetMapping("/userDataList")
    public ResultData userDataList(int type, int page, int limit) {
        //构造分页以及条件查询器
        LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUserData::getType, type);
        //查询yddUserData表 得到集合数据--目标得到ids
        List<YddUserData> list = yddUserDataService.list(queryWrapper);
        ArrayList<Integer> ids = new ArrayList<>();
        for (YddUserData yddUserData : list) {
            ids.add(yddUserData.getArticleId());
        }
        //拿到ids之后  构建分页以及条件
        Page<YddArticle> yddArticlePage = new Page<>(page, limit);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(YddArticle::getId, ids);
        Page<YddArticle> pageInfo = yddArticleService.page(yddArticlePage, wrapper);
        //pageInfo里面缺少cateName  拷贝&补充
        Page<ArticleDto> yddArticleDtoPage = new Page<>();

        BeanUtils.copyProperties(pageInfo, yddArticleDtoPage, "records");
        List<YddArticle> records = pageInfo.getRecords();
        //新建集合用来替代pageInfo中的records
        ArrayList<ArticleDto> yddArticleDtos = new ArrayList<>();

        for (YddArticle record : records) {
            ArticleDto yddArticleDto = new ArticleDto();
            BeanUtils.copyProperties(record, yddArticleDto);
            //添加缺少的cateName
            Integer cateId = record.getCateid();
            LambdaQueryWrapper<YddCate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(YddCate::getId, cateId);
            YddCate one = yddCateService.getOne(lambdaQueryWrapper);
            yddArticleDto.setCatename(one.getCatename());
            yddArticleDtos.add(yddArticleDto);
        }
        //将yddArticleDtoPage中确实的集合数据填充
        yddArticleDtoPage.setRecords(yddArticleDtos);

        //将数据进行封装
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", (int) yddArticleDtoPage.getTotal());
        map.put("totalPages", (int) yddArticleDtoPage.getPages());
        map.put("pageSize", (int) limit);
        map.put("currentPage", (int) yddArticleDtoPage.getCurrent());
        map.put("data", yddArticleDtoPage.getRecords());

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list", map);

        //返回执行结果
        return ResultData.ok("", hashMap);
    }

    /**
     * 点赞或收藏  在YddUserData中加入  private String action 属性;
     * @param type
     * @param article_id
     * @param action
     * @return
     */
    @GetMapping("/userDataHandle")
    public  ResultData userDataHandle(int type,int article_id,String action){
        log.info("传来的数据为:{}{}{}",type,article_id,action);
        //TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), YddUserData.class);
        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), YddUserData.class);
        //创建构造器
        LambdaUpdateWrapper<YddUserData> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(YddUserData::getArticleId,article_id);
        lambdaUpdateWrapper.eq(YddUserData::getType,type);
        lambdaUpdateWrapper.set(YddUserData::getAction,action);
        yddUserDataService.update(lambdaUpdateWrapper);
        return  ResultData.ok("","操作成功");
    }

    @GetMapping("/getUserInfo")
    public ResultData getUserInfo(HttpServletRequest request) {
        //----------------------------------------
        String token = request.getHeader("token");
        System.out.println(token);
        Claims claims = JwtUtils.getClaims(token);
        int userId = (int) claims.get("userId");


        //int currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getId, userId);
        //获取存取之后的数据--userInfo
        YddUser one = yddUserService.getOne(wrapper);
        //获取发布的文章数量--articleNum
        LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUserData::getUserId, one.getId());
        int articleCount = yddUserDataService.count(queryWrapper);
        //获取点赞数量 type=2
        int num1 = count(2,userId);
        //收藏数量  type=1
        int num2 = count(1,userId);

        //进行组装返回
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userInfo", one);
        hashMap.put("articleNum", articleCount);
        hashMap.put("zanNum", num1);
        hashMap.put("collectNum", num2);

        //返回成功标志
        return ResultData.ok("", hashMap);


    }
    /**
     * 点赞收藏的数量统计
     * @param type
     * @return
     */
    public int count(int type,int id) {
        LambdaQueryWrapper<YddUserData> yddUserDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yddUserDataLambdaQueryWrapper.eq(YddUserData::getType,type);
        yddUserDataLambdaQueryWrapper.eq(YddUserData::getUserId,id);
        int num = yddUserDataService.count(yddUserDataLambdaQueryWrapper);
        return num;

    }
}
